import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import mk from '@traptitech/markdown-it-katex';
// import '../../assets/code-highlight.css'
import Clipboard  from "clipboard";
// import {ElMessage} from "element-plus";
const clipboard = new Clipboard('.copy-class', {
    text: function(trigger) {
        const str = trigger.getAttribute('data-clipboard-text') || '完蛋了，没复制出来'
        return decodeURIComponent(str)
    }
})
clipboard.on('success', (e) => {
    // ElMessage({
    //     type: 'success',
    //     message: '复制成功'
    // })
    e.clearSelection();
})

const md = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
    breaks: true,
    highlight: function (str, lang) {
        if(lang === 'ets'){
            lang = 'typescript'
        }
        // @ts-ignore
        if (lang && hljs.getLanguage(lang)) {
            try {
                return ('<pre class="hljs" style="white-space: pre-wrap;overflow-x: auto;overflow-scrolling: touch;width: inherit; padding: 0 0.5rem; line-height: 1.2rem">' +
                    '<div style="text-align: right; font-size: 0.8rem"> ' + lang +
                    ' <span class="copy-class"  style="cursor: pointer" data-clipboard-text="' + encodeURIComponent(str.toString()) + '" >复制代码</span>' +
                    '</div><code style="line-height: 1.5rem">' + hljs.highlight(lang, str).value + '</code></pre>').trim();
            } catch (e) {
                console.error('markdown解析错误')
                console.error(e)
            }
        }
        return '<pre class="hljs" style="white-space: pre-wrap;"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
    }
});
md.use(mk, {"blockClass": "math-block", "errorColor" : " #cc0000"});
export default function useFormatMarkdown(str){
    // console.log(md.render(str),'str')
    return md.render(str)
}